<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="10">
          <px-col :span="6">
            <px-form-item label="计划编号" prop="planNo">
              <px-input
                v-model="queryParams.planNo"
                placeholder="请输入计划编号"
                maxlength="50"
                clearable
                @blur="queryParams.planNo = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="任务编号" prop="taskNo">
              <px-input
                v-model="queryParams.taskNo"
                placeholder="请输入任务编号"
                maxlength="50"
                clearable
                @blur="queryParams.taskNo = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <EquipSystemTree
              :className="queryParams.className"
              :systemCode="queryParams.systemCode"
              @changeAllSystemCodes="changeAllSystemCodes"
              @changeSystemCodes="changeSystemCodes"
              @clearSystem="clearSystem"
            />
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备名称" prop="eqpId">
              <px-input
                v-model="queryParams.eqpId"
                placeholder="请输入设备名称"
                clearable
                maxlength="50"
                @blur="queryParams.eqpId = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="来源" prop="unnormalSource">
              <px-select v-model="queryParams.unnormalSource" placeholder="请选择任务来源" clearable filterable>
                <px-option v-for="item in faultSourceList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="状态" prop="taskStatus">
              <px-select
                v-model="queryParams.taskStatus"
                placeholder="请选择状态"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                clearable
                filterable
              >
                <px-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="执行人" prop="executorId">
              <px-select-v2
                v-model="queryParams.executorId"
                style="width: 100%"
                filterable
                clearable
                :options="approvalList"
                placeholder="请选择执行人"
              />
            </px-form-item>
          </px-col>

          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 353px)" border>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'status'" #default="scope">
            <div class="status">
              <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.taskStatus]}` }" />
              <p :style="{ color: `${tagBgColorList[scope.row.taskStatus]}` }">
                {{ scope.row.taskStatusDesc }}{{ scope.row.timeOut ? "(超期)" : "" }}
              </p>
            </div>
          </template>
          <template v-else-if="item.type === 'link'" #default="scope">
            <span
              v-if="isHasPermission('ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_DETAIL')"
              style="color: #3b82f6; cursor: pointer"
              @click="handleView(scope.row)"
            >
              {{ scope.row.taskNo }}
            </span>
            <span v-else>{{ scope.row.taskNo }}</span>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="(scope.row.executorId === userId || scope.row.planCreateBy === userId) && scope.row.taskStatus === 2"
              content="转派"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_FORWARD'" link type="primary" icon="Position" @click="handleForward(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.executorId === userId && scope.row.taskStatus === 2" content="执行任务" placement="top">
              <px-button
                v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_EXECUTE'"
                link
                type="primary"
                icon="DocumentChecked"
                @click="handleExecute(scope.row)"
              />
            </px-tooltip>
            <px-tooltip v-if="scope.row.taskStatus === 1 && scope.row.planCreateBy === userId" content="取消" placement="top">
              <px-button v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_CANCEL'" link type="primary" icon="CircleClose" @click="handleCancel(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.taskStatus === 1 && scope.row.isInGroup" content="领取任务" placement="top">
              <px-button
                v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_COLLECT'"
                link
                type="primary"
                icon="DocumentAdd"
                @click="handleCollect(scope.row)"
              />
            </px-tooltip>
            <px-tooltip
              v-if="
                scope.row.isTransfer !== 1 &&
                [2, 3].includes(scope.row.taskStatus) &&
                (scope.row.planCreateBy === userId || scope.row.executorId === userId)
              "
              content="转维修任务"
              placement="top"
            >
              <px-button
                v-has="'ALL_EQUIP_MAINTAIN_EXCEPTION_TASK_MAINTAIN'"
                link
                type="primary"
                icon="Memo"
                @click="handleToMaintainTask(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <TaskFinishDetail
      :isMain="isMain"
      :isView="isView"
      :userId="userId"
      :taskNo="taskNo"
      :taskStatus="taskStatus"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
      @handleExecute="handleExecute"
    />
    <ExecuteTask
      :isMain="isMain"
      :isView="isView"
      :isFresh="isFresh"
      :userId="userId"
      :taskNo="taskNo"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <ForwardDialog :visible="isForwardShow" :rowData="rowData" @closeDialog="isForwardShow = false" @queryTable="queryTable" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_MAINTAIN_EXCEPTION_TASK"
});
import { queryDictData } from "@/api/common";
import { cancelExceptionTask, getExceptionTaskList } from "@/api/equip/exception";
import { isHasPermission } from "@/utils/auth";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import ExecuteTask from "./components/ExecuteTask.vue";
import ForwardDialog from "./components/ForwardDialog.vue";
import TaskFinishDetail from "./components/TaskFinishDetail.vue";

const router = useRouter();
const route = useRoute();

const searchFormRef = ref();

const state = reactive<any>({
  userId: "",
  isMain: true, // 主页面true 详情页面false
  isView: false, // 查看true 新增/编辑false
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "taskNo", label: "任务（工单）编号", minWidth: "150", type: "link", showOverflowTooltip: true, fixed: "left" },
    { prop: "planNo", label: "所属计划编号", minWidth: "150", showOverflowTooltip: true, fixed: "left" },
    { prop: "eqpId", label: "设备编号", minWidth: "180", showOverflowTooltip: true },
    { prop: "eqpName", label: "设备名称", minWidth: "150", showOverflowTooltip: true },
    { prop: "startTime", label: "开始时间", minWidth: "150", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "80", showOverflowTooltip: true },
    { prop: "systemCodeDesc", label: "系统", minWidth: "120", showOverflowTooltip: true },
    { prop: "taskStatusDesc", label: "状态", minWidth: "100", type: "status", showOverflowTooltip: true },
    { prop: "groupCodeName", label: "点检执行组", minWidth: "120", showOverflowTooltip: true },
    { prop: "executorName", label: "执行人", minWidth: "120", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  drawerType: "add",
  taskNo: "",
  taskStatus: 0,
  systemCodes: [],
  faultSourceList: [],
  approvalList: [],
  statusList: [], // 工单状态
  isForwardShow: false,
  rowData: {},
  isFresh: false
});
const {
  userId,
  isMain,
  isView,
  queryParams,
  tableColumns,
  tableData,
  total,
  drawerType,
  taskNo,
  taskStatus,
  systemCodes,
  faultSourceList,
  statusList,
  approvalList,
  isForwardShow,
  rowData,
  isFresh
} = toRefs(state);

const tagBgColorList = {
  0: "#909399", // 取消
  1: "#F59E0B", // 待接单
  2: "#3B82F6", // 执行中
  3: "#10B981" // 已完成
};

// 获取字典下拉列表
const queryClassNameSelect = async () => {
  statusList.value = await queryDictData({ typeCode: "POINT_CHECK_TASK_STATUS" });
  faultSourceList.value = await queryDictData({ typeCode: "POINT_CHECK_SOURCE" });
};

// 查询列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  params.systemCodes = systemCodes.value;
  const data = await getExceptionTaskList({ ...params });
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
};
// 重置筛选条件列表
const resetTable = async () => {
  searchFormRef.value.resetFields();
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  queryTable();
};

// 进入页面时触发
onMounted(async () => {
  const { planNo, taskNo: taskNum, taskStatus: status, className } = route.query;
  if (planNo) {
    queryParams.value.planNo = planNo;
  }
  if (className) {
    queryParams.value.className = className;
    queryParams.value.taskStatus = status ? (status as string)?.split("-") : [];
  }
  if (taskNum && taskStatus) {
    taskNo.value = taskNum;
    taskStatus.value = +status;
    isMain.value = false;
    isView.value = true;
  }
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  approvalList.value = await getEmployeeIdAndName();
  queryTable();
  queryClassNameSelect();
});

// 详情
const handleView = (row: any) => {
  taskNo.value = row.taskNo;
  taskStatus.value = row.taskStatus;
  isMain.value = false;
  isView.value = true;
};

// 执行
const handleExecute = (row: any, fresh?: boolean) => {
  taskNo.value = row.taskNo;
  isMain.value = false;
  isView.value = false;
  if (fresh) {
    isFresh.value = true;
  }
};

// 转派
const handleForward = (row: any) => {
  isForwardShow.value = true;
  rowData.value = row;
};

// 领取任务
const handleCollect = (row: any) => {
  taskNo.value = row.taskNo;
  taskStatus.value = row.taskStatus;
  isMain.value = false;
  isView.value = true;
};

const handleToMaintainTask = (row: any) => {
  router.push(`/all/equip/maintain/task?exception=${row.taskNo}`);
};
const handleCancel = (row: any) => {
  PxMessageBox.confirm(`确认取消该任务吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await cancelExceptionTask(row.taskNo);
      PxMessage.success("取消成功");
      queryTable();
    })
    .catch(() => {});
};

// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  rowData.value = {};
  taskNo.value = "";
  isMain.value = true;
  drawerType.value = "";
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
